<template>
  <v-container grid-list-lg pa-0>
    <v-layout wrap>
      <!-- 作文输入部分 -->
      <v-flex xs12>
        <v-basic-card title="作文上传与分析" toolbar-height="56" class="pa-4">
          <template slot="card-content">
            <v-select
                v-model="selectedEssayType"
                :items="essayTypes"
                label="选择作文类型"
                outlined
                dense
                @change="handleTypeChange"
            ></v-select>

            <v-textarea
                v-model="localEssay"
                label="请在此粘贴您的作文"
                outlined
                rows="12"
                placeholder="请输入您的作文内容..."
                class="mt-4"
            ></v-textarea>

            <v-btn @click="submitEssay" color="primary" class="mt-4">
              提交作文分析
            </v-btn>
          </template>
        </v-basic-card>
      </v-flex>

      <PersonalizedReport
          v-if="Boolean(userEssay && userEssay.trim())"
      />


      <LogicalStructureAnalysis
          ref="logicalStructureAnalysis"
          v-if="Boolean(userEssay && userEssay.trim())"
          :essayCategory="selectedEssayType"
      />

      <TransitionWordsNetwork v-if="Boolean(userEssay && userEssay.trim())" />

    </v-layout>
  </v-container>
</template>

<script>
import PersonalizedReport from './PersonalizedReport.vue';
import LogicalStructureAnalysis from './LogicalStructureAnalysis.vue';
import TransitionWordsNetwork from './TransitionWordsNetwork.vue';
import { mapGetters, mapActions } from "vuex";

export default {
  name: 'EssayUpload',
  data() {
    return {
      essayTypes: ['小作文', '大作文'],
      selectedEssayType: '小作文',
      localEssay: '',    // ✅ 初始化为空字符串

      logicData: {},         // 初始化为空对象
      vocabData: [],         // 初始化为空数组
      transitionData: []     // 初始化为空数组
    };
  },
  computed: {
    ...mapGetters(['userEssay']),
  },
  methods: {
    ...mapActions(['setUserEssay','clearAnalysisData']),
    async submitEssay() {
      if (!this.localEssay.trim()) {
        alert("请先输入您的作文");
        return;
      }

      try {
        console.log("提交作文：", this.localEssay);

        // ✅ Vuex 数据更新
        await this.setUserEssay(this.localEssay);

        console.log("当前 Vuex 中的 userEssay：", this.userEssay);

        // ✅ 强制子组件更新，确保渲染逻辑触发
        this.$nextTick(() => {
          if (this.$refs.logicalStructureAnalysis) {
            console.log("触发 detectEssayGenre 方法");
            this.$refs.logicalStructureAnalysis.detectEssayGenre(this.userEssay, this.selectedEssayType);
          }
        });

      } catch (error) {
        console.error("保存作文失败：", error);
      }
    },
    /**
     * 处理作文类型切换
     */
    handleTypeChange(newType) {
      console.log("作文类型切换为：", newType);
      this.selectedEssayType = newType;

      this.$nextTick(() => {
        if (this.$refs.logicalStructureAnalysis) {
          console.log("切换类型，触发 detectEssayGenre 方法");
          this.$refs.logicalStructureAnalysis.detectEssayGenre(this.userEssay, this.selectedEssayType);
        }
      });
    },
    handleLogout() {
      console.log("用户退出，清空 Vuex 数据");
      this.clearAnalysisData();
    },

    /**
     * 页面刷新时清空数据
     */
    handlePageReload() {
      console.log("页面刷新，清空 Vuex 数据");
      this.clearAnalysisData();
    }
  },
  mounted() {
    window.addEventListener('beforeunload', this.handlePageReload);
  },

  beforeDestroy() {
    window.removeEventListener('beforeunload', this.handlePageReload);
  },
  components: {
    PersonalizedReport,
    LogicalStructureAnalysis,
    TransitionWordsNetwork
  },

};
</script>
